import React, { useState, useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom';
import ContentTitle from "@/components/contentTitle/ContentTitle";
import { Form, Input, InputNumber, Select, message, Upload, Button } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { getGoodsType, updateGoods } from "@/api/goods";
import { baseUrl } from "@/utile/commen.js";
const beforeUpload = file => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
};
export default function GoodsEidt() {
    const [loading, setLoading] = useState(false);
    const { TextArea } = Input;
    const { state } = useLocation();
    const navigate = useNavigate();
    const [goodsInfo, setGoodsInfo] = useState({
        name: '',
        category: '',
        price: '',
        imgUrl: '',
        goodsDesc: '',
        id: '',
    })
    const [types, setTypes] = useState([
        {
            key: '1',
            label: '',
            value: ''
        }
    ])
    const [imgUrl, setImgUrl] = useState('');

    useEffect(() => {
        setGoodsInfo(state)
        setImgUrl(state.imgUrl)
        getTypes();
    }, [])
    const getTypes = async () => {
        const { categories } = await getGoodsType();
        const newData = categories.map((item, index) => {
            return {
                label: item.cateName,
                value: item.cateName,
                key: index
            }
        })
        setTypes(newData)
    }
    const handleChange = info => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            setImgUrl(info.file.response.imgUrl);
            setLoading(false);
        }
    };
    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </button>
    );
    const onFinish = async (values) => {
        values = { ...values, id: goodsInfo.id };
        // 处理图片路径
        const index = imgUrl.lastIndexOf('/');
        values.imgUrl = imgUrl.slice(index + 1);
        console.log(values);
        const { code, msg } = await updateGoods(values);
        if (code === 0) {
            message.success(msg);
            navigate('/home/goodsList')
        } else {
            message.error(msg);
        }
    }
    return (
        <>
            <ContentTitle title="商品编辑" />
            {
                goodsInfo.id ?
                    <Form
                        name='goodsEidt'
                        initialValues={goodsInfo}
                        style={{ marginTop: 20, width: '100%' }}
                        onFinish={onFinish}
                    >
                        <Form.Item label="商品名称" name={"name"} style={{ height: 40 }}>
                            <Input style={{ height: 40 }} />
                        </Form.Item >
                        <Form.Item label="商品分类" name={"category"} style={{ height: 40 }}>
                            <Select
                                style={{ width: 180, height: 40, }}
                                // onChange={handleChange}
                                options={types}
                            />
                        </Form.Item>
                        <Form.Item label="商品价格" name={"price"} style={{ height: 40 }}>
                            <InputNumber addonBefore="+" addonAfter="-" style={{ width: 180, height: 40 }} />
                        </Form.Item>
                        <Form.Item label="商品图片" name={"imgUrl"} >
                            <Upload
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action={"/poo/goods/goods_img_upload"}
                                beforeUpload={beforeUpload}
                                onChange={handleChange}
                            >
                                {imgUrl ? <img src={baseUrl + imgUrl} alt="avatar" style={{ width: '100%', height: '100%' }} /> : uploadButton}
                            </Upload>
                        </Form.Item>
                        <Form.Item label="商品描述" name={"goodsDesc"} style={{ width: '100%' }}>
                            <TextArea rows={3} />
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" style={{ height: '40px', marginLeft: '70px' }}>
                                立即修改
                            </Button>
                        </Form.Item>
                    </Form> : ''
            }
        </>
    )
}
